package g_proxy.c_protection;

import java.lang.reflect.Proxy;

/**
 * Created by wug on 2016/7/5 0005.
 */
public class MainTest {
    public static void main(String[] args) {
        HeroService garen = new HeroServiceImpl("盖伦");

        System.out.println(garen.getName() + "|" + garen.getAttackForce() + "|" + garen.getBlood());
        HeroService garenEquipmentProxy = getEquipmentProxy(garen);
        HeroService garenAttrackedProxy = getAttrackedHander(garen);
        // 通过代理装备护甲
        garenEquipmentProxy.equipment(new Armor());

        HeroService yi = new HeroServiceImpl("易");
        HeroService yiEquipmentProxy = getEquipmentProxy(yi);
        HeroService yiAttrackedProxy = getAttrackedHander(yi);
        // 通过代理装备刀
        yiEquipmentProxy.equipment(new Sword());

        System.out.println(garen.getName() + "|" + garen.getAttackForce() + "|" + garen.getBlood());
        System.out.println(yi.getName() + "|" + yi.getAttackForce() + "|" + yi.getBlood());

        garenAttrackedProxy.attacked(yi.getAttackForce());

        System.out.println(garen.getName() + "|" + garen.getAttackForce() + "|" + garen.getBlood());
        /**
         * 这里就是代理的保护
         * 代理通过 攻击代理阻止了 传装备的操作
         */
        garenAttrackedProxy.equipment(new Sword());

        /**
         * 还能通过代理控制 get set方法 按照规则自订义 等等
         */
    }

    /**
     * 通过反射的方式获取 装备代理 （也有动态代理的说法）
     * @param heroService
     * @return
     */
    public static HeroService getEquipmentProxy(HeroService heroService) {
        return (HeroService)Proxy.newProxyInstance(
                heroService.getClass().getClassLoader(),
                heroService.getClass().getInterfaces(),
                new EquipmentHandler(heroService));
        /**
         * 代理对象是如何创建出来的？看这边文章有源码分析
         * https://www.zybuluo.com/pastqing/note/174679
         */
    }

    /**
     * 通过反射的方式获取 被攻击代理 （也有动态代理的说法）
     * @param heroService
     * @return
     */
    public static HeroService getAttrackedHander(HeroService heroService) {
        return (HeroService)Proxy.newProxyInstance(
                heroService.getClass().getClassLoader(),
                heroService.getClass().getInterfaces(),
                new AttackedHandler(heroService));
    }
}
